package com.webemail.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.webemail.sys.model.SysFolder;
import com.webemail.sys.model.SysLabel;
import com.webemail.sys.model.SysLabelMessage;
import com.webemail.sys.model.SysMessageFolder;
import com.webemail.sys.service.EmailService;
import com.webemail.sys.service.FolderService;
import com.webemail.sys.service.LabelMessageService;
import com.webemail.sys.service.LabelService;
import com.webemail.sys.service.MessageDeletedService;
import com.webemail.sys.service.MessageDraftsService;
import com.webemail.sys.service.MessageFolderService;
import com.webemail.sys.service.MessageInboxService;
import com.webemail.sys.service.MessageJunkService;
import com.webemail.sys.service.MessageSendService;
import com.webemail.sys.util.CommonUtils;
import com.webemail.sys.util.LayuiBean;
import com.webemail.sys.util.MailConnect.FolderType;
import com.webemail.sys.util.ResultBean;

@Controller
@RequestMapping("/folder")
public class EmailFolderController {
	@Resource
	private EmailService emailService;
	@Resource
	private FolderService folderService;
	@Resource
	private LabelMessageService labelMessageService;
	@Resource
	private LabelService labelService;
	@Resource
	private MessageDeletedService messageDeletedService;
	@Resource
	private MessageDraftsService messageDraftsService;
	@Resource
	private MessageFolderService messageFolderService;
	@Resource
	private MessageInboxService messageInboxService;
	@Resource
	private MessageJunkService messageJunkService;
	@Resource
	private MessageSendService messageSendService;

	private Logger logger = LoggerFactory.getLogger(getClass());
	private static String saveURL = "http://localhost:8080/mail";
	private static String saveFolder = "uploadFiles";
	private static String folderName = "文件夹";

	private int getUserId() {
		return 1;
	}

	@RequestMapping("/page")
	@ResponseBody
	public String emailRevicePage(HttpServletRequest request, Model model) {
		String colomn = CommonUtils.getString(request.getParameter("colomn"));
		String word = CommonUtils.getString(request.getParameter("word"));
		long userId = this.getUserId();
		long folderId = 0;
		int page = 0;
		int limit = 10;
		LayuiBean<SysMessageFolder> layuiBean;
		try {
			page = Integer.parseInt(CommonUtils.getString(request.getParameter("page")));
		} catch (Exception e) {
			e.printStackTrace();
			page = 0;
		}
		if (page > 0) {
			page--;
		}
		try {
			limit = Integer.parseInt(CommonUtils.getString(request.getParameter("limit")));
		} catch (Exception e) {
			e.printStackTrace();
			limit = 10;
		}
		try {
			folderId = Long.parseLong(CommonUtils.getString(request.getParameter("folderId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<SysMessageFolder> result = messageFolderService.listByPage(userId, folderId,colomn,word, page * limit, limit, 0, 2);
		long size = messageFolderService.count(userId, folderId,colomn,word, 0, 2);
		layuiBean = new LayuiBean<>(0, "SUCC", size, result);
		return JSON.toJSONString(layuiBean);
	}

	@RequestMapping("/read")
	@ResponseBody
	public String emailRead(HttpServletRequest request, Model model) {
		String messageIds = CommonUtils.getString(request.getParameter("messageIds"));
		int read = Integer.parseInt(CommonUtils.getString(request.getParameter("read")));
		if (this.readMessage(messageIds, read, FolderType.SentFolder)) {
			return JSON.toJSONString(new ResultBean(1, "修改成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "修改失败", null));
		}
	}

	/**
	 * 
	 * @param messageIds
	 * @param read
	 * @param folderType
	 * @return
	 */
	private boolean readMessage(String messageIds, int read, FolderType folderType) {
		long userId = this.getUserId();
		String messageId[] = messageIds.split(",");
		int count = 0;
		for (int i = 0; i < messageId.length; i++) {
			long tempId = Long.parseLong(messageId[i]);
			SysMessageFolder message = messageFolderService.get(tempId, userId);
			if (read == 0) {
				message.setHasRead("false");
			} else {
				message.setHasRead("true");
			}
			int result = messageFolderService.update(message);
			if (result > 0) {
				count++;
			}
		}
		if (count == messageId.length) {
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String emailDelete(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1) {
			return JSON.toJSONString(new ResultBean(0, "删除失败", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i].trim());
				SysMessageFolder message = messageFolderService.get(messageId, userId);
				if (message != null && message.getId() > 0) {
					message.setState((long) 1);
					if (messageFolderService.update(message) > 0) {
						succIds.add(message.getId());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "删除成功", succIds));
		} else {

		}
		return JSON.toJSONString(new ResultBean(0, "删除失败", succIds));
	}

	@RequestMapping("/moveFolder")
	@ResponseBody
	public String emailMoveFolder(HttpServletRequest request, Model model) {

		String[] messageIds = null;
		long folderId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			folderId = Long.parseLong(CommonUtils.getString(request.getParameter("folderId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || folderId < 1) {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
		SysFolder folder = folderService.get(folderId, userId);
		if (folder == null || folder.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "文件夹不存在", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageFolder message = messageFolderService.get(messageId, userId);
				SysMessageFolder messageFolder = new SysMessageFolder();
				messageFolder.setUserId(userId);
				messageFolder.setMailId(message.getMailId());
				messageFolder.setFolder(folder.getName());
				messageFolder.setFolderId(folder.getId());
				messageFolder.setMessageId(message.getMessageId());
				messageFolder.setSubject(message.getSubject());
				messageFolder.setBodyText(message.getBodyText());
				messageFolder.setSentDate(message.getSentDate());
				messageFolder.setSentDateTime(message.getSentDateTime());
				messageFolder.setSize(message.getSize());
				messageFolder.setMailFrom(message.getMailFrom());
				messageFolder.setHasAttachment(message.getHasAttachment());
				messageFolder.setAttachment(message.getAttachment());
				messageFolder.setHasRead(message.getHasRead());
				messageFolder.setIsDefaultFolder("false");
				messageFolder.setHasReply(message.getHasReply());
				messageFolder.setLabel(message.getLabel());
				messageFolder.setSource(message.isLocalSource());
				messageFolder.setState((long) 0);
				messageFolderService.insert(messageFolder);
				message.setState((long) 3);
				messageFolderService.update(message);
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "移动成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
	}

	@RequestMapping("/addLabel")
	@ResponseBody
	public String emailAddLabel(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long labelId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			labelId = Long.parseLong(CommonUtils.getString(request.getParameter("labelId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || labelId < 1) {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
		SysLabel label = labelService.get(labelId, userId);
		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageFolder message = messageFolderService.get(messageId, userId);
				SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
						folderName);
				if (labelMessage == null || labelMessage.getId() < 1) {
					labelMessage = new SysLabelMessage();
					labelMessage.setLabelId(label.getId() + "");
					labelMessage.setMessageId(message.getId() + "");
					labelMessage.setTable(folderName);
					labelMessage.setUserId(userId);
					labelMessageService.insert(labelMessage);
				}
				if (!CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
					if (StringUtils.isBlank(message.getLabel())) {
						message.setLabel(label.getName());
					} else {
						message.setLabel(message.getLabel() + "," + label.getName());
					}
					messageFolderService.update(message);
				}
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "添加成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
	}

	@RequestMapping("/deleteLabel")
	@ResponseBody
	public String emailRemoveLabel(HttpServletRequest request, Model model) {
		long messageId = 0;
		String labelName = "";
		long userId = this.getUserId();
		try {
			messageId = Long.parseLong(CommonUtils.getString(request.getParameter("messageId")));
			labelName = CommonUtils.getString(request.getParameter("labelName"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageId < 1 || StringUtils.isBlank(labelName)) {
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		SysLabel label = labelService.get(userId, labelName);
		if (label == null || label.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "标签不存在", null));
		}
		try {
			SysMessageFolder message = messageFolderService.get(messageId, userId);
			SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
					folderName);
			if (labelMessage != null && labelMessage.getId() > 0) {
				labelMessageService.delete(labelMessage.getId(), userId);
			}
			if (CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
				String[] labels = message.getLabel().trim().split(",");
				ArrayList<String> labelList = new ArrayList<String>();
				for (int i = 0; i < labels.length; i++) {
					if (!labels[i].trim().equalsIgnoreCase(label.getName().trim())) {
						labelList.add(labels[i].trim());
					}
				}
				message.setLabel(StringUtils.join(labelList, ","));
				messageFolderService.update(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		return JSON.toJSONString(new ResultBean(1, "移除成功", null));
	}

}
